//
//  MMSegmentManager.swift
//  MMSegmentManager
//
//  Created by huangweiqiang on 2022/6/27.
//

import UIKit

class MMSegmentManager {
    class func associateHead(header: MMSegmentHeader,
                             scroll: MMSegmentScroll,
                             completion: @escaping (()->Void),
                             changePage: @escaping ((NSInteger)->Void)) {
        let showIndex = (header.showIndex != 0) ? header.showIndex : scroll.showIndex
        header.showIndex = showIndex
        header.defaultAndCreateView()
        header.selectIndex = { aIndex  in
            changePage(aIndex)
            DispatchQueue.main.async {
                scroll.setContentOffset(x: CGFloat(aIndex) * scroll.frame.size.width, animation: true)
            }
        }
        
        scroll.showIndex = showIndex
        scroll.initialView()
        scroll.scrollEnd = { aIndex in
            changePage(aIndex)
            DispatchQueue.main.async {
                header.changeCurrentIndex(index: aIndex, completed: true)
            }
        }
        
        scroll.offsetScale = { offset_x in
            DispatchQueue.main.async {
                header.addObserverSegmentScrollViewDidScrollToPoint(offsetx: offset_x)
            }
        }
        completion()
    }
}
